// pages/cart/cart.js
import {IndexModel} from "../../api/index"
const indexModel = new IndexModel()
import {helper} from "../../utils/helper"
Page({
  data: {
    cartList: [],
    totalPrice : 0,
    totalCount : 0
  },
  onLoad: function (options) {
    this.initData()
  },

  /*初始化出书*/
  initData(){
     //获取本地存储的数据
     const cartList = wx.getStorageSync('cartList');
     this.setData({
       cartList
     });
 
     //调用获取总价方法
     this.getTotalPrice()
  },
  /*跳转到订单页面*/
  goOrder(){
    wx.navigateTo({
      url: '/pages/order/order',
    })
  },

   /*打开扫描二维码方法*/
   doCode(){
    //打开扫码相机
    wx.scanCode({
      onlyFromCamera: true,
      success : res => {
        const {result} = res;
        this.getProduction(result)
      }
    })
  },

  /*获取商品信息方法*/
  getProduction(result){
    indexModel.getProduction(result).then(response=>{
      if(response.data.success){
        //调用添加数据到购物车方法
        helper.addCart(response.data.result[0])

        this.initData()
      }
    }).catch(error=>{
      console.log(error)
    })
  },

  /*减少商品数量*/
  decrment(e){
    let index = e.currentTarget.dataset.index;
    const data = this.data.cartList[index];
  
    if(data.num <= 1){
      wx.showModal({
        title: '提示',
        content: '您确定要删除此商品吗?',
        success :(res)=> {
          if (res.confirm) {
            this.data.cartList.splice(index,1);
            this.setData({
              cartList : this.data.cartList
            })
            wx.setStorageSync('cartList', this.data.cartList)
            this.getTotalPrice()
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      
      return;
    }else{
      data.num -= 1;
      this.setData({
        cartList : this.data.cartList
      })
      wx.setStorageSync('cartList', this.data.cartList)
  
      this.getTotalPrice()
    }
   
  },

  /*增加商品数量*/
  increment(e){
    let index = e.currentTarget.dataset.index;
    const data = this.data.cartList[index];
    data.num += 1;
    this.setData({
      cartList : this.data.cartList
    })
    wx.setStorageSync('cartList', this.data.cartList)
    this.getTotalPrice()
  },

  /*获取总价*/
  getTotalPrice(){
    let data = this.data.cartList;
    let result = 0;
    let count = 0;
    for(var i=0;i<data.length;i++){
      result += (data[i].price * data[i].num)
      count += data[i].num;
    }
    result = result.toFixed(2)
    this.setData({
      totalPrice : result,
      totalCount : count
    })
  },
})